package com.wakala.employment.fragment.finder;

import static com.kongzue.dialogx.dialogs.PopTip.tip;
import static com.xuexiang.xui.utils.XToastUtils.toast;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdate;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.faltenreich.skeletonlayout.Skeleton;
import com.faltenreich.skeletonlayout.SkeletonLayoutUtils;
import com.google.common.collect.Lists;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.Toaster;
import com.kongzue.dialogx.dialogs.CustomDialog;
import com.kongzue.dialogx.dialogs.PopTip;
import com.kongzue.dialogx.interfaces.OnBindView;
import com.leaf.library.StatusBarUtil;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BottomPopupView;
import com.lxj.xpopup.core.CenterPopupView;
import com.stx.xmarqueeview.XMarqueeView;
import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.modelbiz.WXOpenCustomerServiceChat;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.wakala.employment.R;
import com.wakala.employment.adapter.base.FlowTagSimpleAdapter;
import com.wakala.employment.adapter.bean.OptionBean;
import com.wakala.employment.adapter.entity.JobInfoVo;
import com.wakala.employment.adapter.marquee.MarqueeViewAdapter;
import com.wakala.employment.core.BaseFragment;
import com.wakala.employment.core.http.subscriber.NoTipRequestSubscriber;
import com.wakala.employment.databinding.FragmentJobInfoBinding;
import com.wakala.employment.http.TestApi;
import com.wakala.employment.utils.Desensitization;
import com.wakala.employment.utils.ImageUtils;
import com.wakala.employment.utils.ScreenshotUtil;
import com.wakala.employment.widget.sharedialog.ShareDialog;
import com.wakala.employment.widget.sharedialog.bean.ShareData;
import com.wakala.employment.widget.sharedialog.interfaces.OnShareClick;
import com.xuexiang.xaop.annotation.SingleClick;
import com.xuexiang.xhttp2.XHttpProxy;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.enums.CoreAnim;
import com.xuexiang.xpage.utils.GsonUtils;
import com.xuexiang.xui.utils.DensityUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.flowlayout.FlowTagLayout;
import com.xuexiang.xutil.app.AppUtils;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.tip.ToastUtils;
import com.yechaoa.yutils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * create an instance of this fragment.
 */
@Page(anim = CoreAnim.none)
public class JobInfoFragment extends BaseFragment<FragmentJobInfoBinding> implements View.OnClickListener {

    public static final String TAG = JobInfoFragment.class.getSimpleName();

    private Skeleton skeleton;

    private Long jobInfoId;

    private JobInfoVo mJobInfoVo;

    private LatLng centerSHpoint = new LatLng(31.238068, 121.501654);// 上海市经纬度

    private double latitude = 34.295248;
    private double longitude = 108.816847;

    private AMap aMap;
    private MapView mapView;
    public AMapLocationClient mLocationClient = null;
    public AMapLocationClientOption mLocationOption = null;

    @NonNull
    @Override
    protected FragmentJobInfoBinding viewBindingInflate(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, boolean attachToRoot) {
        return FragmentJobInfoBinding.inflate(inflater, container, attachToRoot);
    }

    /**
     * @return 返回为 null意为不需要导航栏
     */
    @Override
    protected TitleBar initTitle() {
        TitleBar titleBar = super.initTitle();
        titleBar.setTitle("招工详情");
        titleBar.setTitleColor(R.color.black);
        titleBar.setLeftTextColor(R.color.black);
        titleBar.setLeftImageDrawable(getResources().getDrawable(R.drawable.icon_arrow_back));
        titleBar.setBackgroundResource(R.color.white);//设置标题栏背景颜色
        StatusBarUtil.setDarkMode(getActivity());
        titleBar.addAction(new TitleBar.ImageAction(R.drawable.icon_share) {
            @Override
            @SingleClick
            public void performAction(View view) {
                jobShare();
            }

            @Override
            public int rightPadding() {
                return DensityUtils.dp2px(getContext(), 10);
            }
        });
        /*titleBar.addAction(new TitleBar.ImageAction(R.drawable.icon_service) {
            @Override
            @SingleClick
            public void performAction(View view) {
                String appId = "wxe8a910123413ba65"; // 填移动应用(App)的 AppId
                IWXAPI api = WXAPIFactory.createWXAPI(requireContext(), appId);
                // 判断当前版本是否支持拉起客服会话
                if (api.getWXAppSupportAPI() >= Build.SUPPORT_OPEN_CUSTOMER_SERVICE_CHAT) {
                    WXOpenCustomerServiceChat.Req req = new WXOpenCustomerServiceChat.Req();
                    req.corpId = "wwa201bef9182dd47e";							      // 企业微信 ID
                    req.url = "https://work.weixin.qq.com/kfid/kfc1a000ec98182ebd4";	// 企业微信 客服URL
                    api.sendReq(req);
                }else {
                    toast("没有安装微信或版本太低");
                }

            }
        });*/
        //设置状态栏背景颜色，如果设置为 Color.TRANSPARENT 将会隐藏状态栏
        getActivity().getWindow().setStatusBarColor(getResources().getColor(R.color.white));
        return titleBar;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        assert getArguments() != null;
        jobInfoId = getArguments().getLong("jobInfoId");
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        mapView = view.findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);// 此方法必须重写
        if (aMap == null) {
            aMap = mapView.getMap();
        }
      /*  try {
            mLocationClient = new AMapLocationClient(getContext());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setOnceLocation(false);
        mLocationOption.setNeedAddress(true);

        mLocationClient.setLocationOption(mLocationOption);
        mLocationClient.setLocationListener(locationListener);

        mLocationClient.startLocation();*/
       /* CameraPosition cameraPosition = new CameraPosition(new LatLng(latitude, longitude), 15, 0, 30);
        //CameraPosition cameraPosition = new CameraPosition(centerSHpoint, 15, 0, 30);
        CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(cameraPosition);
        aMap.moveCamera(cameraUpdate);
        drawMarkers();*/
       /* MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(centerSHpoint);
        aMap.addMarker(markerOptions);*/
        return view;
    }

    //画定位标记图
    public void drawMarkers(double latitude, double longitude) {
        //
        CameraPosition cameraPosition = new CameraPosition(new LatLng(latitude, longitude), 15, 0, 30);
        //CameraPosition cameraPosition = new CameraPosition(centerSHpoint, 15, 0, 30);
        CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(cameraPosition);
        aMap.moveCamera(cameraUpdate);
        //
        MarkerOptions markerOptions = new MarkerOptions()
                .position(new LatLng(latitude, longitude))
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_dingwei))
                .draggable(true);
        Marker marker = aMap.addMarker(markerOptions);
        marker.showInfoWindow();
    }

    @Override
    protected void initViews() {
        skeleton = SkeletonLayoutUtils.createSkeleton(binding.contentRoot);
        skeleton.showSkeleton();
        init();
    }

    /**
     * 初始化AMap对象
     */
    private void init() {
       /* if (aMap == null) {
            aMap = mapView.getMap();
        }*/
//        MarkerOptions markerOptions = new MarkerOptions();
//        markerOptions.position(centerSHpoint);
//        aMap.addMarker(markerOptions);
//        initLocation();
    }

    private void initLocation() {
        //初始化定位
        try {
            AMapLocationClient.updatePrivacyShow(getContext(), true, true);
            AMapLocationClient.updatePrivacyAgree(getContext(), true);
            mLocationClient = new AMapLocationClient(getContext());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //设置定位回调监听

    }

    @Override
    protected void initListeners() {
        //下拉刷新
        binding.smartRefresh.setOnRefreshListener(refreshLayout -> {
            getUserJobInfo(jobInfoId);
            // TODO: 2020-02-25 这里只是模拟了网络请求
            /*refreshLayout.getLayout().postDelayed(() -> {
                //mJobsAdapter.refresh(DemoDataProvider.getDemoJobInfos());
                refreshLayout.finishRefresh();
            }, 1000);*/
        });
        binding.smartRefresh.setEnableLoadMore(false);
        binding.smartRefresh.autoRefresh();//第一次进入触发自动刷新，演示效果
        //界面按钮事件绑定
        binding.btnLinkBoss.setOnClickListener(view -> callPhoneWithPermission(binding.btnLinkBoss.getTag() == null ? "0" : binding.btnLinkBoss.getTag().toString()));
        binding.sbLinkBoos.setOnClickListener(view -> callPhoneWithPermission((binding.sbLinkBoos.getTag() == null ? "0" : binding.sbLinkBoos.getTag().toString())));
        //收藏/取消
        binding.ssBtnCollect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                jobCollect();
            }
        });
        //分享
        binding.ssBtnShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                jobShare();
            }
        });
        //投诉举报
        binding.sbComplaint.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                showComplaintDialog();
            }
        });
    }

    /**
     * 投诉举报弹窗
     */
    private void showComplaintDialog() {
        new XPopup.Builder(getContext()).asCustom(new BottomPopupView(requireContext()) {
            @Override
            protected int getImplLayoutId() {
                return R.layout.layout_complaint_report;
            }

            @Override
            protected void onCreate() {
                //初始化 投诉选项
                FlowTagLayout mFlowlayout = findViewById(R.id.flowlayout);
                mFlowlayout.setTagCheckedMode(FlowTagLayout.FLOW_TAG_CHECKED_SINGLE);//单选
                FlowTagSimpleAdapter<OptionBean> tagAdapter = new FlowTagSimpleAdapter<OptionBean>(getContext());
                mFlowlayout.setAdapter(tagAdapter);
                tagAdapter.addTags(getComplaintOptionList());
                //投诉内容
                EditText etComplaintContent = findViewById(R.id.edit_content_commit);
                //取消按钮
                findViewById(R.id.btn_cancel_commit).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dismiss();
                    }
                });
                //提交按钮
                findViewById(R.id.btn_confirm_commit).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if(mFlowlayout.getSelectedItem()==null){
                            Toaster.showLong("请选择投诉原因");
                            return;
                        }else if(StringUtils.isEmpty(etComplaintContent.getText().toString())){
                            Toaster.showLong("请输入投诉内容");
                            return;
                        }
                        dismiss();
                        tip(R.drawable.icon_success, "感谢您的反馈，我们会认证审核处理.");
                    }
                });

            }
        }).show();
    }
    private List<OptionBean> getComplaintOptionList() {
        List<OptionBean> list = new ArrayList<>();
        list.add(new OptionBean("1", "虚假信息"));
        list.add(new OptionBean("2", "诈骗信息"));
        list.add(new OptionBean("3", "信息地址不符"));
        list.add(new OptionBean("4", "已招满/不要人"));
        list.add(new OptionBean("5", "电话空号/停机"));
        list.add(new OptionBean("6", "其他"));
        return list;
    }

    @Override
    public void onClick(View view) {

    }

    @SuppressLint("CheckResult")
    private void getUserJobInfo(Long jobInfoId) {
        skeleton.showSkeleton();
        XHttpProxy.proxy(TestApi.IJobService.class)
                .getUserJobInfoById(jobInfoId)
                .subscribeWith(new NoTipRequestSubscriber<JobInfoVo>() {
                    @Override
                    protected void onSuccess(JobInfoVo jobInfoVo) {
                        Log.i(TAG, "-------------招工信息详情------------------");
                        if (null != jobInfoVo) {
                            mJobInfoVo = jobInfoVo;
                            bindData(jobInfoVo);
                            Log.i(TAG, GsonUtils.toJson(jobInfoVo));
                            binding.smartRefresh.finishRefresh();
                            Toaster.show("信息列表已刷新");
                            drawMarkers(Double.parseDouble(jobInfoVo.getJobLat()), Double.parseDouble(jobInfoVo.getJobLng()));
                            skeleton.showOriginal();
                        }
                        //ToastUtils.toast("已更新最新数据");
                        Log.i(TAG, "-------------招工信息详情------------------");
                    }

                    @Override
                    public void onError(ApiException e) {
                        super.onError(e);
                        ToastUtils.toast(e.getDisplayMessage());
                        Log.i(TAG, "-------------招工信息详情-返回错误------------------");
                        Log.e(TAG, e.getMessage());
                        skeleton.showOriginal();
                    }

                });
    }

    private void bindData(JobInfoVo jobInfoVo) {
        //头像
        RequestOptions options = new RequestOptions()
                .centerCrop()
                .placeholder(R.color.color_f4)
                .diskCacheStrategy(DiskCacheStrategy.ALL);
        Glide.with(binding.ivUserAvatar.getContext()).load(jobInfoVo.getUser().getAvatar())
                .apply(options)
                .into(binding.ivUserAvatar);
        //名称
        binding.tvUserName.setText(jobInfoVo.getLinkMan());
        binding.tvTitle.setText(jobInfoVo.getTitle());
        binding.tvSummary.setText(Html.fromHtml(jobInfoVo.getContent(), Html.FROM_HTML_MODE_COMPACT));
        binding.tvPublishTime.setText(jobInfoVo.getPublishTime().substring(0, 16));
        binding.tvJobCity.setText(jobInfoVo.getJobUserAddress().getProvince() + jobInfoVo.getJobUserAddress().getCity());
        binding.tvLocation.setText(jobInfoVo.getJobUserAddress().getProvince() + jobInfoVo.getJobUserAddress().getCity()
                + jobInfoVo.getJobUserAddress().getDistrict() + jobInfoVo.getJobUserAddress().getDetail());
        //jobInfoVo.setLinkPhone(jobInfoVo.getLinkPhone().substring(0,3)+"********");
        binding.btnLinkBoss.setTag(jobInfoVo.getLinkPhone());
        binding.sbLinkBoos.setTag(jobInfoVo.getLinkPhone());
        jobInfoVo.setLinkPhone(Desensitization.mobilePhoneDesensitization(jobInfoVo.getLinkPhone()));
        if (jobInfoVo.getUser().getRealNameAuth()) {
            binding.fgIsAuthed.setVisibility(View.VISIBLE);
            binding.tvJobLinkPhone1.setVisibility(View.VISIBLE);
            binding.tvJobLinkPhone2.setVisibility(View.GONE);
            binding.tvJobLinkPhone1.setText(jobInfoVo.getLinkPhone());
        } else {
            binding.fgIsAuthed.setVisibility(View.GONE);
            binding.tvJobLinkPhone1.setVisibility(View.GONE);
            binding.tvJobLinkPhone2.setVisibility(View.VISIBLE);
            binding.tvJobLinkPhone2.setText(jobInfoVo.getLinkPhone());
        }
        if (jobInfoVo.getUser().getEnterpriseAuth()) {
            binding.fgIsAuthedEnterprise.setVisibility(View.VISIBLE);
        } else {
            binding.fgIsAuthedEnterprise.setVisibility(View.GONE);
        }
        //收藏处理
        if (jobInfoVo.getUserJobRecord() != null) {
            Drawable dra = null;
            Resources res = getResources();
            if (jobInfoVo.getUserJobRecord().getHasCollect()) {
                dra = res.getDrawable(R.drawable.icon_star_fill_king);

            } else {
                dra = res.getDrawable(R.drawable.icon_star_larger);
            }
            //调用setCompoundDrawables时，必须调用Drawable.setBounds()方法,否则图片不显示
            dra.setBounds(0, 0, dra.getMinimumWidth(), dra.getMinimumHeight());
            binding.ssBtnCollect.setCompoundDrawables(null, dra, null, null);
        }
        //-------顶部微信模块
        List<String> data = new ArrayList<>();
        data.add("免费加入本地招人找活群");
        data.add("附件找人找活信息推送");
        data.add("优质创业项目推荐");
        data.add("超多赚钱机会分享");

        XMarqueeView xMarqueeView = (XMarqueeView) findViewById(R.id.marquee);
        try {
            xMarqueeView.setAdapter(new MarqueeViewAdapter(data, getContext()));
        } catch (Exception e) {
            //catchsetAdapter重复设置adapter抛出异常的异常。
            Log.w("", e.getMessage());
        }
        binding.rbWeiChat.setOnClickListener(view -> {
            //打开关注微信界面
           /* if (AppUtils.isInstallApp("com.tencent.mm")) {
                try {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse("weixin://dl/officialaccount?officialAccountID=" + "miaoyankeji"));
                    startActivity(intent);
                } catch (Exception e) {
                    // 处理异常情况
                    PopTip.show("打开微信失败");
                }
            } else {
                PopTip.show("本机没有安装微信");
            }*/
            ToastUtil.showToast("下滑关闭当前窗口");
            new XPopup.Builder(getContext()).asCustom(new BottomPopupView(requireContext()) {
                @Override
                protected int getImplLayoutId() {
                    return R.layout.dialog_invite_view;
                }

                @Override
                protected void onCreate() {
                    super.onCreate();

                }
            }).show();
        });
        //---
        //Tag容器
        com.xuexiang.xui.widget.flowlayout.FlowLayout tagLayout = findViewById(R.id.tag_layout);
        tagLayout.removeAllViews();
        //判断实名认证
        if (jobInfoVo.getUser().getRealNameAuth()) {
            addTag(tagLayout, "已实名", "blue");
        }
        if (jobInfoVo.getUser().getEnterpriseAuth()) {
            addTag(tagLayout, "企业认证", "blue");
        }
        //添加薪资
        addTag(tagLayout, jobInfoVo.getSalaryName(), "blue");
        for (String tag : jobInfoVo.getJobTagsList()) {
            addTag(tagLayout, tag, "blue");
        }
        for (String tag : jobInfoVo.getWelfareTagsList()) {
            addTag(tagLayout, tag, "gray");
        }
        for (String tag : jobInfoVo.getKeywordsList()) {
            addTag(tagLayout, tag, "gray");
        }
        //--------------------------------
    }

    private void addTag(com.xuexiang.xui.widget.flowlayout.FlowLayout linearLayout, String tagName, String themName) {
        TextView textView = new TextView(linearLayout.getContext());
        ViewGroup.MarginLayoutParams textViewParams = new ViewGroup.MarginLayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, // 宽度
                ViewGroup.LayoutParams.WRAP_CONTENT  // 高度
        );
        textViewParams.setMargins(DensityUtils.dp2px(getContext(), 5), 0, 0, DensityUtils.dp2px(getContext(), 5));
        textView.setPadding(DensityUtils.dp2px(getContext(), 2), DensityUtils.dp2px(getContext(), 2), DensityUtils.dp2px(getContext(), 2), DensityUtils.dp2px(getContext(), 2));
        textView.setLayoutParams(textViewParams);
        textView.setText(tagName);
        textView.setTextSize(12.0f);

        if ("blue".equals(themName)) {
            textView.setBackgroundColor(linearLayout.getResources().getColor(R.color.tag_bg_blue));
            textView.setTextColor(linearLayout.getResources().getColor(R.color.colorPrimary));
        } else if ("gray".equals(themName)) {
            textView.setBackgroundColor(linearLayout.getResources().getColor(R.color.tag_bg_gray));
            textView.setTextColor(linearLayout.getResources().getColor(R.color.tag_text_gray));
        } else {
            textView.setBackgroundColor(linearLayout.getResources().getColor(R.color.tag_bg_blue));
            textView.setTextColor(linearLayout.getResources().getColor(R.color.colorPrimary));
        }
        linearLayout.addView(textView);
    }

    private void callPhoneWithPermission(String phoneNumber) {
        if (phoneNumber.equals("0")) {
            return;
        }
        XXPermissions.with(this)
                // 申请单个权限
                .permission(Permission.CALL_PHONE)
                // 设置权限请求拦截器（局部设置）
                //.interceptor(new PermissionInterceptor())
                // 设置不触发错误检测机制（局部设置）
                //.unchecked()
                .request(new OnPermissionCallback() {

                    @Override
                    public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                        if (!allGranted) {
                            toast("获取部分权限成功，但部分权限未正常授予");
                            return;
                        }
                        //toast("获取录音和日历权限成功");
                        //startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+phoneNumber)));
                        //startActivity(new Intent(Intent.ACTION_CALL_BUTTON));
                        CustomDialog.show(new OnBindView<CustomDialog>(R.layout.layout_custom_dial_phone_dialog) {
                            @Override
                            public void onBind(final CustomDialog dialog, View v) {
                                Button btnOk;
                                btnOk = v.findViewById(R.id.btn_ok);
                                ImageView imgClose = v.findViewById(R.id.img_close);
                                imgClose.setOnClickListener(view -> dialog.dismiss());
                                btnOk.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneNumber)));
                                        dialog.dismiss();
                                    }
                                });
                            }
                        }).setMaskColor(getResources().getColor(R.color.translucent_background));
                    }

                    @Override
                    public void onDenied(@NonNull List<String> permissions, boolean doNotAskAgain) {
                        if (doNotAskAgain) {
                            toast("被永久拒绝授权，请手动授予录音和日历权限");
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(getContext(), permissions);
                        } else {
                            toast("获取录音和日历权限失败");
                        }
                    }
                });
    }

    /**
     * 职位收藏
     *
     * @param jobInfoId
     */
    @SuppressLint("CheckResult")
    private void handleCollect(Long jobInfoId) {
        appLoadingDialog.show();
        XHttpProxy.proxy(TestApi.IOther.class)
                .collect(jobInfoId, 0)
                .subscribeWith(new NoTipRequestSubscriber<String>() {
                    @Override
                    protected void onSuccess(String string) {
                        Log.i(TAG, "-------------招工信息详情------------------");
                        appLoadingDialog.dismiss();
                        //ToastUtils.toast("已更新最新数据");
                        Log.i(TAG, "-------------招工信息详情------------------");
                    }

                    @Override
                    public void onError(ApiException e) {
                        super.onError(e);
                        ToastUtils.toast(e.getDisplayMessage());
                        Log.i(TAG, "-------------招工信息详情-返回错误------------------");
                        Log.e(TAG, e.getMessage());
                        appLoadingDialog.dismiss();
                    }

                });
    }

    /**
     * 收藏处理
     */
    private void jobCollect() {
        mJobInfoVo.getUserJobRecord().setHasCollect(!mJobInfoVo.getUserJobRecord().getHasCollect());
        Drawable dra = null;
        Resources res = getResources();
        if (mJobInfoVo.getUserJobRecord().getHasCollect()) {
            dra = res.getDrawable(R.drawable.icon_star_fill_king);

        } else {
            dra = res.getDrawable(R.drawable.icon_star_larger);
        }
        //调用setCompoundDrawables时，必须调用Drawable.setBounds()方法,否则图片不显示
        dra.setBounds(0, 0, dra.getMinimumWidth(), dra.getMinimumHeight());
        binding.ssBtnCollect.setCompoundDrawables(null, dra, null, null);
        //
        handleCollect(mJobInfoVo.getId());
    }

    /**
     * 分享处理
     */
    private void jobShare() {
        List<ShareData> shareDataList = new ArrayList<>();
        shareDataList.add(new ShareData(getContext(), "微信", R.drawable.icon_wexin_cicly_round));
        shareDataList.add(new ShareData(getContext(), "朋友圈", R.drawable.icon_wexin_friend_round));
        shareDataList.add(new ShareData(getContext(), "复制链接", R.drawable.icon_link_round));
        shareDataList.add(new ShareData(getContext(), "生成海报", R.drawable.icon_poster_round));

        ShareDialog.build()
                .setShareDataList(shareDataList)
                .show(new OnShareClick() {
                    /*
                     * 此处为回调，
                     * @param context       返回上下文
                     * @param shareData     返回点击的 ShareData 实例
                     * @param shareButton   返回按钮
                     * @param index         返回索引
                     * @return 为 true 时，不自动关闭对话框
                     */
                    @Override
                    public boolean onClick(Context context, ShareData shareData, View shareButton, int index) {
                        //Toast.makeText(getContext(), shareData.getLabel() + " Click!", Toast.LENGTH_SHORT).show();
                        if(shareData.getLabel().equals("微信")){
                          try {
                              new ShareAction(getActivity())
                                      .setPlatform(SHARE_MEDIA.WEIXIN)//传入平台
                                      .withText("河狸帮-招工找活")//分享内容
                                      .withMedia(new UMImage(getContext(), R.drawable.app_logo))
                                      .setCallback(umShareListener)//回调监听器
                                      .share();
                          }catch (Exception e){
                              Toast.makeText(getContext(), "分享失败"+e.getMessage(), Toast.LENGTH_SHORT).show();
                          }
                        }else if(shareData.getLabel().equals("朋友圈")){
                            new ShareAction(getActivity())
                                    .setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE)
                                    .withMedia(new UMImage(getContext(), R.drawable.app_logo))//传入平台
                                    .withText(getResources().getString(R.string.app_name))//分享内容
                                    .setCallback(umShareListener)//回调监听器
                                    .share();
                        } else if (shareData.getLabel().equals("复制链接")) {
                            Toast.makeText(getContext(), shareData.getLabel() + "已复制链接!", Toast.LENGTH_SHORT).show();
                        } else if (shareData.getLabel().equals("生成海报")) {
                            //ScreenshotUtil.getBitmapByView(getContext(), (ScrollView) findViewById(R.id.main_scrollview));
                            new XPopup.Builder(getContext()).asCustom(new BottomPopupView(requireContext()) {
                                @Override
                                protected int getImplLayoutId() {
                                    return R.layout.dialog_share_view;
                                }

                                @Override
                                protected void onCreate() {
                                    super.onCreate();
                                    findViewById(R.id.tvDismiss).setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            dismiss();
                                        }
                                    });
                                    TextView tvWX = findViewById(R.id.tvWX);
                                    TextView tvWXFriends = findViewById(R.id.tvWXFriends);
                                    TextView tvDownCode = findViewById(R.id.tvDownCode);
                                    tvWX.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            shareWxImage();
                                            dismiss();
                                        }
                                    });
                                    tvWXFriends.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                            shareWxFriendsImage();
                                            dismiss();
                                        }
                                    });
                                    tvDownCode.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                            Bitmap originBitmap= BitmapFactory.decodeResource(getResources(),R.drawable.hlb_poster_bg01);
                                            ImageUtils.INSTANCE.saveImageToGallery(getContext(), originBitmap);
                                            dismiss();
                                        }
                                    });

                                }
                            }).show();
                        }
                        return false;
                    }
                });

    }

    public void shareText() {
       /* new ShareAction(getActivity()).withText("hello").setDisplayList(SHARE_MEDIA.SINA,SHARE_MEDIA.QQ,SHARE_MEDIA.WEIXIN)
                .setCallback(umShareListener).open();*/
        new ShareAction(getActivity())
                .setPlatform(SHARE_MEDIA.WEIXIN)//传入平台
                .withText("hello")//分享内容
                .setCallback(umShareListener)//回调监听器
                .share();
    }
    public void shareWxImage() {
        new ShareAction(getActivity())
                .setPlatform(SHARE_MEDIA.WEIXIN)//传入平台-微信好友
                .withText("河狸帮")//分享内容
                .withMedia(new UMImage(getContext(), R.drawable.hlb_poster_bg01))
                .setCallback(umShareListener)//回调监听器
                .share();
    }
    public void shareWxFriendsImage() {
        new ShareAction(getActivity())
                .setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE)//传入平台-微信朋友圈
                .withText("河狸帮")//分享内容
                .withMedia(new UMImage(getContext(), R.drawable.hlb_poster_bg01))
                .setCallback(umShareListener)//回调监听器
                .share();
    }

    private final UMShareListener umShareListener = new UMShareListener() {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {
            Toast.makeText(getContext(), "分享开始", Toast.LENGTH_LONG).show();
        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {
            Toast.makeText(getContext(), "成功了", Toast.LENGTH_LONG).show();
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(getContext(), "失败" + t.getMessage(), Toast.LENGTH_LONG).show();
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(getContext(), "取消了", Toast.LENGTH_LONG).show();

        }
    };

}